package com.ksd.modules.advert.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ksd.common.core.exception.KsdBusinessException;
import com.ksd.common.enums.DeletedEnums;
import com.ksd.common.enums.StatusEnums;
import com.ksd.common.po.BatchIdsPO;
import com.ksd.common.web.model.SystemInfo;
import com.ksd.common.web.threadlocal.SystemIdThrealLocal;
import com.ksd.commons.BaseServiceImpl;
import com.ksd.modules.advert.entity.AdminAdvert;
import com.ksd.modules.advert.mapper.AdminAdvertMapper;
import com.ksd.modules.advert.po.AdminAdvertSavePO;
import com.ksd.modules.advert.po.AdminAdvertSearchPO;
import com.ksd.modules.advert.service.IAdminAdvertService;
import com.ksd.modules.advert.service.IAdminAdvertisementService;
import com.ksd.modules.advert.vo.AdvertisementVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章表 服务实现类
 * </p>
 *
 * @author Auto Generator
 * @since 2023-08-16
 */
@Service
public class AdminAdvertService extends BaseServiceImpl<AdminAdvertMapper, AdminAdvert> implements IAdminAdvertService {
    @Resource
    private IAdminAdvertisementService iAdminAdvertisementService;

    /**
     * 查询首页分类接口
     *
     * @return
     */
    @Override
    public Page<AdminAdvert> findAdvert(AdminAdvertSearchPO adminAdvertSearchPO) {
        LambdaQueryWrapper<AdminAdvert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminAdvert::getSystemId, SystemIdThrealLocal.get().getSystemId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminAdvertSearchPO.getStatus()), AdminAdvert::getStatus, adminAdvertSearchPO.getStatus());
        lambdaQueryWrapper.eq(Objects.nonNull(adminAdvertSearchPO.getType()), AdminAdvert::getType, adminAdvertSearchPO.getType());
        lambdaQueryWrapper.eq(Objects.nonNull(adminAdvertSearchPO.getAdvertiserId()), AdminAdvert::getAdvertiserId, adminAdvertSearchPO.getAdvertiserId());
        lambdaQueryWrapper.eq(Objects.nonNull(adminAdvertSearchPO.getDeleted()), AdminAdvert::getIsDeleted, adminAdvertSearchPO.getDeleted());
        if (StringUtils.isNotEmpty(adminAdvertSearchPO.getKeyword())) {
            lambdaQueryWrapper.and(c -> c.like(AdminAdvert::getSkipTitle, adminAdvertSearchPO.getKeyword())
                    .or().like(AdminAdvert::getAdvertiserName, adminAdvertSearchPO.getKeyword())
                    .or().like(AdminAdvert::getName, adminAdvertSearchPO.getKeyword())
                    .or().like(AdminAdvert::getSkipModel, adminAdvertSearchPO.getKeyword()));
        }
        lambdaQueryWrapper.orderByAsc(AdminAdvert::getSorted);
        // 查询返回
        Page<AdminAdvert> page = new Page<>(adminAdvertSearchPO.getPageNo(), adminAdvertSearchPO.getPageSize());
        return this.page(page, lambdaQueryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveUpdateAdvert(AdminAdvertSavePO adminAdvertSavePO) {
        AdminAdvert adminAdvert = tranferBo(adminAdvertSavePO, AdminAdvert.class);
        adminAdvert.setSystemId(SystemIdThrealLocal.get().getSystemId());
        adminAdvert.setSystemName(SystemIdThrealLocal.get().getSystemName());
        return this.saveOrUpdate(adminAdvert);
    }

    @Override
    public boolean deleteAdvertById(Long id) {
        AdminAdvert adminAdvert = new AdminAdvert();
        adminAdvert.setIsDeleted(DeletedEnums.DELETED.getCode());
        adminAdvert.setId(id);
        adminAdvert.setStatus(StatusEnums.UN_STATUS.getCode());
        return this.updateById(adminAdvert);
    }

    @Override
    public AdminAdvert getAdvertById(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean updateStatus(Long id, String column, Integer value) {
        return super.updateStatus(id, column, value);
    }

    @Override
    public List<AdvertisementVo> getHomeAdvert(Integer functionType) {
        SystemInfo systemInfo = SystemIdThrealLocal.get();
        LambdaQueryWrapper<AdminAdvert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminAdvert::getType, functionType);
        lambdaQueryWrapper.eq(AdminAdvert::getStatus, StatusEnums.STATUS.getCode());
        lambdaQueryWrapper.eq(AdminAdvert::getIsDeleted, DeletedEnums.UN_DELETED.getCode());
        lambdaQueryWrapper.eq(AdminAdvert::getSystemId, systemInfo.getSystemId());
        lambdaQueryWrapper.le(AdminAdvert::getStartTime, LocalDateTime.now());
        lambdaQueryWrapper.ge(AdminAdvert::getEndTime, LocalDateTime.now());
        lambdaQueryWrapper.orderByAsc(AdminAdvert::getSorted);
        List<AdminAdvert> list = this.list(lambdaQueryWrapper);
        return BeanUtil.copyToList(list, AdvertisementVo.class);
    }

    @Override
    public List<AdvertisementVo> getAdvert(Long categoryId, Integer functionType) {
        SystemInfo systemInfo = SystemIdThrealLocal.get();
        LambdaQueryWrapper<AdminAdvert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminAdvert::getType, functionType);
        lambdaQueryWrapper.eq(AdminAdvert::getStatus, StatusEnums.STATUS.getCode());
        lambdaQueryWrapper.eq(AdminAdvert::getIsDeleted, DeletedEnums.UN_DELETED.getCode());
        lambdaQueryWrapper.eq(AdminAdvert::getSystemId, systemInfo.getSystemId());
        lambdaQueryWrapper.le(AdminAdvert::getStartTime, LocalDateTime.now());
        lambdaQueryWrapper.ge(AdminAdvert::getEndTime, LocalDateTime.now());
        return BeanUtil.copyToList(this.list(lambdaQueryWrapper), AdvertisementVo.class);
    }

    /**
     * @param id
     * @param sorted
     * @return
     */
    @Override
    public boolean changeCategoryAdvertSort(Long id, Integer sorted) {
        AdminAdvert adminAdvert = this.getById(id);
        if (Objects.nonNull(adminAdvert) && !adminAdvert.getSorted().equals(sorted)) {
            LambdaQueryWrapper<AdminAdvert> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(AdminAdvert::getIsDeleted, DeletedEnums.UN_DELETED.getCode());
            lambdaQueryWrapper.eq(AdminAdvert::getType, adminAdvert.getType());
            lambdaQueryWrapper.eq(AdminAdvert::getSorted, sorted);
            long count = this.count(lambdaQueryWrapper);
            if (count > 0) {
                throw new KsdBusinessException("该分类下位置【" + sorted + "】已被占用!");
            }

            AdminAdvert adminAdvert2 = new AdminAdvert();
            adminAdvert2.setId(id);
            adminAdvert2.setSorted(sorted);
            return this.updateById(adminAdvert2);
        }

        return false;
    }


    /**
     * 批量删除-物理删除
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean batchRemoves(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeBatchByIds(ids);
    }

    /**
     * 批量逻辑恢复
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean batchRecovers(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminAdvert> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", DeletedEnums.UN_DELETED.getCode());
        updateWrapper.in("id", ids);
        return this.update(updateWrapper);
    }

    /**
     * 批量删除-逻辑删除
     *
     * @param batchIdsPO
     * @return
     */
    @Override
    public Boolean bacthDels(BatchIdsPO batchIdsPO) {
        if (StringUtils.isEmpty(batchIdsPO.getIds())) {
            return false;
        }

        // 把文章进行恢复
        List<Long> ids = Arrays.stream(batchIdsPO.getIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        UpdateWrapper<AdminAdvert> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", DeletedEnums.DELETED.getCode());
        updateWrapper.in("id", ids);
        return this.update(updateWrapper);
    }


    @Override
    public boolean removeAdvertById(Long id) {
        return this.removeById(id);
    }

    /**
     * 恢复删除
     *
     * @param id
     * @return
     */
    @Override
    public boolean recoverAdvertById(Long id) {
        AdminAdvert adminAdvert = new AdminAdvert();
        adminAdvert.setIsDeleted(DeletedEnums.UN_DELETED.getCode());
        adminAdvert.setId(id);
        return this.updateById(adminAdvert);
    }

    /**
     * 复制
     * @param opid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean copyData(Long opid){
        AdminAdvert data = this.getById(opid);
        if(Objects.nonNull(data)){
            data.setId(null);
            data.setStatus(0);
            data.setCreateTime(LocalDateTime.now());
            data.setUpdateTime(LocalDateTime.now());
            data.setName(data.getName()+"[副本]");
            this.save(data);
        }
        return true;
    }
}
